package read1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.function.Function;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class BaiduYuyin extends Pages implements Reader {
    private static final String apiKey = "YF6YsFYDQx1FAEL4Dr5AbY9V";  
    private static final String secretKey = "289c1f2f0ec5579f83be97934da05cf2";  
    private static final String cuid = getLocalMac();  
    private Logger log = Logger.getLogger(this.getClass());
    
    private static String token = "";
    
    public BaiduYuyin() {
    	super();
    	getToken();
    }
    
    public void speak(String message) {
    	if(message.isEmpty()) {
    		return;
    	}
    	String URLToRead = "http://tsn.baidu.com/text2audio?tex=" + message + "&lan=zh&cuid=" + cuid + "&ctp=1&tok=" + token;
    	driver.get(URLToRead);
    	waitForMediaEnd();
    }
    
    public void waitForMediaEnd() {
    	try {
    		driver.findElement(By.name("media"));
    	} catch (NoSuchElementException e) {
    		log.error("Cannot read the url: " + driver.getCurrentUrl());
    		log.error("page source is: " + driver.getPageSource());
    		return;
    	}
    	try {
	    	new WebDriverWait(driver, 20).until(
	    	    ExpectedConditions.jsReturnsValue("return document.getElementsByName('media')[0].ended==true;")
	    	);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }

    private static void getToken(){  
        String getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +   
            "&client_id=" + apiKey + "&client_secret=" + secretKey;  
        HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(getTokenURL).openConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}  
        try {
			token = new JSONObject(printResponse(conn)).getString("access_token");
		} catch (Exception e) {
			e.printStackTrace();
		}  
    }
    
    private static String printResponse(HttpURLConnection conn) throws Exception {  
        if (conn.getResponseCode() != 200) {  
            // request error  
            System.out.println("conn.getResponseCode() = " + conn.getResponseCode());  
            return "";  
        }  
        InputStream is = conn.getInputStream();  
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));  
        String line;  
        StringBuffer response = new StringBuffer();  
        while ((line = rd.readLine()) != null) {  
            response.append(line);  
            response.append('\r');  
        }  
        rd.close();  
        System.out.println(new JSONObject(response.toString()).toString(4));  
        return response.toString();  
    }
    
	private static String getLocalMac() {
		InetAddress ia = null;
		try {
			ia = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		//获取网卡，获取地址
		byte[] mac = null;
		try {
			mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		System.out.println("mac数组长度："+mac.length);
		StringBuffer sb = new StringBuffer("");
		for(int i=0; i<mac.length; i++) {
			if(i!=0) {
				sb.append("-");
			}
			//字节转换为整数
			int temp = mac[i]&0xff;
			String str = Integer.toHexString(temp);
			System.out.println("每8位:"+str);
			if(str.length()==1) {
				sb.append("0"+str);
			}else {
				sb.append(str);
			}
		}
		return sb.toString();
	}

	public void read(List<String> messages) {
		if(messages!=null) {
			for(String message: messages) {
				if(!message.isEmpty()) {
					speak(message);
				}
			}
		}
	}
}
